<template>
    <div class="department">
        <div class="search">
            <el-form :inline="true" :model="searchData" size="mini" class="demo-form-inline">

                <el-form-item label="部门名称:">
                    <el-input v-model="searchData.name" placeholder="请输入部门名称"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="search">查询</el-button>
                    <el-button type="primary" @click="add(1)">添加部门</el-button>
                    <el-button type="primary" @click="look">查看系统管理组</el-button>
                </el-form-item>
            </el-form>
        </div>

        <div class='content'>
            <!-- 添加、编辑 -->
            <el-dialog :title="dialogtitle" :visible.sync="centerDialogVisible" width="600px" center @close="dialogclose">
                <el-form :model="dform" :rules="rules" ref="dform" label-width="140px" class="demo-ruleForm" size="mini">
                    <el-form-item label="部门名称" prop="name">
                        <el-input v-model="dform.name" placeholder="请输入"></el-input>
                    </el-form-item>
                    <el-form-item label="部门类型" prop="type">
                        <el-select v-model="dform.type" placeholder="请选择部门类型">
                            <el-option v-for="(item,index) in optionType" :key="index" :label="item.label" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="部门负责人" prop="charge">
                        <el-select v-model="dform.charge" placeholder="请选择部门负责人">
                            <el-option v-for="(item,index) in userType" :key="index" :label="item.u_username" :value="item.u_id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="部门联系电话" prop="tel">
                        <el-input v-model="dform.tel" placeholder="例：13312123232  或者  7394466"></el-input>
                    </el-form-item>
                    <el-form-item label="上班打卡时间" prop="to_work_time">
                        <el-time-picker placeholder="上班时间" v-model="dform.to_work_time" :editable="false" value-format="HH:mm" format="HH:mm"></el-time-picker>
                    </el-form-item>
                    <el-form-item label="下班打卡时间" prop="after_work_time">
                        <el-time-picker placeholder="下班时间" v-model="dform.after_work_time" :editable="false" value-format="HH:mm" format="HH:mm"></el-time-picker>
                    </el-form-item>
                    <el-form-item label="部门地址" prop="address">
                        <el-input v-model="dform.address" placeholder="请输入"></el-input>
                    </el-form-item>
                    <el-form-item label="部门月应收业绩指标" prop="receivable">
                        <el-input type="number" v-model="dform.receivable" placeholder="请输入"></el-input>
                    </el-form-item>
                    <el-form-item label="部门月实收业绩指标" prop="received">
                        <el-input type="number" v-model="dform.received" placeholder="请输入"></el-input>
                    </el-form-item>

                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="cancel('dform')" size="mini">取 消</el-button>
                    <el-button type="primary" @click="submit('dform')" size="mini">确 定</el-button>
                </span>
            </el-dialog>
            <div class='list'>
                <el-table ref="multipleTable" :data="list.data" tooltip-effect="dark" style="width: 100%" highlight-current-row>

                    <!-- <el-table-column align="center" prop="c_id" label="公司ID" width="120"></el-table-column>
                    <el-table-column align="center" prop="id" label="部门ID" width="120"></el-table-column> -->
                    <el-table-column align="center" prop="name" label="部门名称" width="120"></el-table-column>
                    <el-table-column align="center" :formatter="typeFun" prop="type" label="部门类型" width="120"></el-table-column>
                    <el-table-column align="center" prop="tel" label="部门电话" width="120"></el-table-column>
                    <el-table-column align="center" prop="address" label="部门地址" width="120"></el-table-column>
                    <el-table-column align="center" prop="u_username" label="部门负责人" width="120"></el-table-column>
                    <el-table-column align="center" prop="receivable" label="部门月应收业绩指标" width="120"></el-table-column>
                    <el-table-column align="center" prop="received" label="部门月实收业绩指标" width="120"></el-table-column>
                    <el-table-column align="center" prop="to_work_time" label="上班时间" width="120"></el-table-column>
                    <el-table-column align="center" prop="after_work_time" label="下班时间" width="120"></el-table-column>
                    <el-table-column align="center" prop="updated_at" label="部门更新时间" width="140"></el-table-column>
                    <el-table-column align="center" prop="created_at" label="部门添加时间" width="140"></el-table-column>
                    <el-table-column fixed="right" label="操作" width="120">
                    <template slot-scope="scope">
                        <el-button @click.native.prevent="lookgrounp(scope.row)" type="text" size="small" style="margin-left: 15px;">三级部门</el-button>
                        <el-button @click.native.prevent="edit(scope.row,1)" type="text" size="small">编辑</el-button>
                        <el-button @click.native.prevent="deltest(scope.row,1)" type="text" size="small">删除</el-button>
                    </template>
                    </el-table-column>
                </el-table>
                <!-- 分页 -->
                <el-pagination :current-page="current" @current-change="handleCurrentChange" :total="list.total" style="margin-top:30px;"></el-pagination>
            </div>
            <!-- authories为该部门的权限   permissionId: 被修改的id  typeid:1为部门，2为员工  -->
            <Permission v-if="showPermission" :authories="d_authories" :permissionId="departmentId" typeid="1" @refreshlistevent="refreshlistievent" />
        </div>

        <!-- 三级部门 -->
        <el-dialog title="三级部门" :visible.sync="grounpcenterDialogVisible" width="800px" center>

            <el-button type="primary" @click="add(2)" size="small" style="margin-bottom: 25px;">添加三级部门</el-button>

            <el-table ref="multipleTable" :data="grounplist.data" tooltip-effect="dark" style="width: 100%" highlight-current-row>

                <el-table-column align="center" prop="name" label="部门名称" width="120"></el-table-column>
                <el-table-column align="center" :formatter="typeFun" prop="type" label="部门类型" width="120"></el-table-column>
                <el-table-column align="center" prop="tel" label="部门电话" width="120"></el-table-column>
                <el-table-column align="center" prop="address" label="部门地址" width="150"></el-table-column>
                <el-table-column align="center" prop="u_username" label="部门负责人" width="120"></el-table-column>
                <el-table-column align="center" prop="receivable" label="部门月应收业绩指标" width="150"></el-table-column>
                <el-table-column align="center" prop="received" label="部门月实收业绩指标" width="150"></el-table-column>
                <el-table-column align="center" prop="to_work_time" label="上班时间" width="120"></el-table-column>
                <el-table-column align="center" prop="after_work_time" label="下班时间" width="120"></el-table-column>
                <el-table-column align="center" prop="updated_at" label="部门更新时间" width="140"></el-table-column>
                <el-table-column align="center" prop="created_at" label="部门添加时间" width="140"></el-table-column>
                <el-table-column fixed="right" label="操作" width="120">
                <template slot-scope="scope">
                    <el-button @click.native.prevent="edit(scope.row,2)" type="text" size="small">编辑</el-button>
                    <el-button @click.native.prevent="deltest(scope.row,2)" type="text" size="small">删除</el-button>
                </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination :current-page="groundcurrent" @current-change="groundhandleCurrentChange" :total="grounplist.total" style="margin-top:30px;"></el-pagination>
        </el-dialog>
    </div>
</template>
<style>
    .home .view-content{
        width: 87%;
    }
</style>

<script>
    // import "../../style/department.css"
    import conf from '../../config/userconf.js'
    import permconfig from '../../config/permconfig.js'
  export default {
    data() {
        var validatePhone = (rule,value,callback) => {    //正则手机号

            var MobileRegex = /^1[3|4|5|7|8][0-9]{9}$/;
            if (!MobileRegex.test(value)) {
                callback(new Error('手机号格式不正确！'))
            } else {
                callback();
            }
        };
        var validateTel = (rule,value,callback) => {    //正则座机号
            var MobileRegex = /(^(\d{3,4}-)\d{7,8}$)|(^\d{7,8}$)/;
            if (!MobileRegex.test(value)) {
                callback(new Error('电话格式不正确！'))
            } else {
                callback();
            }
        };
        return {
            list:[],
            searchData:{
                    c_id:'',
                    name:'',
            },
            dform:{
                d_superior_id: '',
                name:'',
                type:'1',
                tel:'',
                charge:'',
                address:'',
                receivable:'',
                received:'',
                to_work_time: '09:00',
                after_work_time: '18:00',
            },
            optionName:[],  //部门名称
            optionType:[
                {label: '综合', value: '1'},
                {label: '业务', value: '2'},
                {label: '财务', value: '3'},
                {label: '客服', value: '4'},
                {label: '行政', value: '5'},
                {label: '技术', value: '6'},
            ],
            userType:[],  //部门员工
            typeVal: '',
            rules:{
                name: [
                    { required: true, message: '请选择部门名称', trigger: 'blur' }
                ],
                type: [
                    { required: true, message: '请选择部门类型', trigger: 'change' }
                ],
                tel: [
                    { required: false, message: '请输入部门联系电话', trigger: 'blur' },   //必填字段，value不为空时进行校验
                    {
                        validator:(rule,value,callback)=>{
                            if(value != "" && value != null){
                                if(value.length < 11 ){
                                    validateTel(rule,value,callback)
                                }else if(value.length >= 11){
                                    validatePhone(rule,value,callback)
                                }
                                
                            }else{
                                callback();
                            }
                        }, trigger: 'blur'
                    },
                ],
                charge: [
                    { required: false, message: '请选择部门负责人', trigger: 'change' }
                ],
                to_work_time: [
                    { required: true, message: '请选择上班打卡时间', trigger: 'change' }
                ],
                after_work_time: [
                    { required: true, message: '请选择下班打卡时间', trigger: 'change' }
                ],

            },
            multipleSelection: [],
            dialogtitle:'添加部门',
            Timef:true,
            centerDialogVisible:false,
            bmId: '',  //部门id
            current: 1,  //当前页码
            groundcurrent: 1, // 三级部门  页码
            showPermission: false,  //是否拥有设置权限   
            d_authories: '',  //所拥有的权限
            departmentId: '',  //部门id
            systemdata: [],  //系统管理组信息
            systemcenterDialogVisible: false,  //系统管理组弹框
            grounpcenterDialogVisible: false,  //三级部门弹框
            grounplist: [],  //三级部门列表数据
            d_superior_id: '',  //上级部门id
        }
    },
    methods: {
        //接收  子组件事件  
        refreshlistievent(){
            //修改权限成功时，应刷新列表数据
            this.getList();
        },
        /* 列表*/
        getList (data=Object()){
            var ownerPermission = window.localStorage.getItem('authories');
                var arr = ownerPermission.split(',');
                if(arr.indexOf(permconfig.qx_qita_chakanbumen)  == -1){
                    alert('您没有该功能的权限');
                    return;
                }
            data.page = this.current;
            conf.department.list(data,(state,res)=>{
                if (state == 'success'&&res.data.code == 0){
                    this.list = res.data.data   
                }else if(state == 'success'&&res.data.code != 0){
                    if(res.data.code == 401){
                        this.$router.push({name:'login'});   //登陆态失效，跳转至登录页
                    }else if(res.data.code == -404){
                        this.list = [];
                    }else{
                        this.$message({
                            type: 'info',
                            message: res.data.msg
                        });
                    }
                }
            })
        },
        /*查询 */
        search () {
            let data  = this.searchData;
            this.getList(data)
        },
        /*取消 */
        cancel (formName) {
            this.centerDialogVisible = false;

            this.$refs.dform.resetFields();
        },
        /*提交 */
        submit (formName) {

            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.judgeprimise();
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        /*判断提交 */
        judgeprimise (data=Object()) {
            if (this.dialogtitle == '添加部门') {
                conf.department.add(this.dform,(state,res)=>{
                    if (state == 'success'&&res.data.code == 0){
                        this.getList();
                        this.centerDialogVisible = false;
                        this.$message({
                            type: 'success',
                            message: '添加成功!'
                        });
                        this.$refs['dform'].resetFields();
                    }else if(state == 'success'&&res.data.code != 0){
                        if(res.data.code == 401){
                            this.$router.push({name:'login'});   //登陆态失效，跳转至登录页
                        }else{
                            this.$message({
                                type: 'info',
                                message: res.data.msg
                            });
                        }
                    }
                })
            }else if (this.dialogtitle == '修改信息'){
                data = this.dform;
                data.id = this.bmId;
                conf.department.edit(data,(state,res)=>{
                    if (state == 'success'&&res.data.code == 0){
                        this.getList();
                        this.centerDialogVisible = false;
                        this.$message({
                            type: 'success',
                            message: '修改成功!'
                        });
                        this.$refs['dform'].resetFields();
                    }else if(state == 'success'&&res.data.code != 0){
                        if(res.data.code == 401){
                            this.$router.push({name:'login'});   //登陆态失效，跳转至登录页
                        }else{
                            this.$message({
                                type: 'info',
                                message: res.data.msg
                            });
                        }
                    }
                })
            }else if (this.dialogtitle == '添加三级部门') {
                data = this.dform;
                data.d_superior_id = this.d_superior_id;
                conf.department.add(data,(state,res)=>{
                    if (state == 'success'&&res.data.code == 0){
                        this.groundgetList();
                        this.centerDialogVisible = false;
                        this.$message({
                            type: 'success',
                            message: '添加成功!'
                        });
                        this.$refs['dform'].resetFields();
                    }else if(state == 'success'&&res.data.code != 0){
                        if(res.data.code == 401){
                            this.$router.push({name:'login'});   //登陆态失效，跳转至登录页
                        }else{
                            this.$message({
                                type: 'info',
                                message: res.data.msg
                            });
                        }
                    }
                })
            }else if (this.dialogtitle == '修改三级部门'){
                data = this.dform;
                data.id = this.bmId;

                conf.department.edit(data,(state,res)=>{
                    if (state == 'success'&&res.data.code == 0){
                        this.groundgetList();
                        this.centerDialogVisible = false;
                        this.$message({
                            type: 'success',
                            message: '修改成功!'
                        });
                        this.$refs['dform'].resetFields();
                    }else if(state == 'success'&&res.data.code != 0){
                        if(res.data.code == 401){
                            this.$router.push({name:'login'});   //登陆态失效，跳转至登录页
                        }else{
                            this.$message({
                                type: 'info',
                                message: res.data.msg
                            });
                        }
                    }
                })
            }
        },
        /*增 */
        add (type) {
             var ownerPermission = window.localStorage.getItem('authories');
                var arr = ownerPermission.split(',');
                if(arr.indexOf(permconfig.qx_qita_tianjiabumen)  == -1){
                    alert('您没有该功能的权限');
                    return;
                }
            if(type == 1){ //部门
                this.dialogtitle = '添加部门';
            }else if(type == 2){  //三级部门
                this.dialogtitle = '添加三级部门';
            }
            this.centerDialogVisible = true;
        },
        // 删除部门
        deltest (row,type,data=Object()) {
             var ownerPermission = window.localStorage.getItem('authories');
                var arr = ownerPermission.split(',');
                if(arr.indexOf(permconfig.qx_qita_shanchubumen)  == -1){
                    alert('您没有该功能的权限');
                    return;
                }

            // console.log(row);
            
            this.$confirm('确认删除 "'+ row.name +'" ?', '删除', {  
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {

                data.id = row.id;
                conf.department.del(data,(state,res)=>{
                    if (state == 'success'&&res.data.code == 0){
                        if(type == 1){ //部门
                            this.getList();
                        }else if(type == 2){  //三级部门
                            this.groundgetList();
                        }
                        
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                    }else if(state == 'success'&&res.data.code != 0){
                        if(res.data.code == 401){
                            this.$router.push({name:'login'});   //登陆态失效，跳转至登录页
                        }else{
                            this.$message({
                                type: 'info',
                                message: res.data.msg
                            });
                        }
                    }
                })

            }).catch(() => {
                this.$message({
                  type: 'info',
                  message: '已取消删除'
                });          
            });
        },
        /**改*/

        edit (val,type) {
            var ownerPermission = window.localStorage.getItem('authories');
            var arr = ownerPermission.split(',');
            if(arr.indexOf(permconfig.qx_qita_xiugaibumen)  == -1){
                alert('您没有该功能的权限');
                return;
            }

            this.dialogtitle = '修改信息';
            if(type == 1){ //部门
                this.dialogtitle = '修改信息';
            }else if(type == 2){  //三级部门
                this.dialogtitle = '修改三级部门';
            }
            this.dform.name = val.name;
            this.dform.type = val.type.toString();
            this.dform.tel = val.tel;
            this.dform.address = val.address;
            this.dform.receivable = val.receivable;
            this.dform.received = val.received;
            this.dform.to_work_time = val.to_work_time;
            this.dform.after_work_time = val.after_work_time;

            if(val.charge == 0){
                this.dform.charge = '';
            }else{
                this.dform.charge = val.charge;
            }
            this.bmId = val.id;
            this.centerDialogVisible = true;
        },
        // 切换页码
        handleCurrentChange(val) {
            this.current = val;
            this.getList();
        },
        //三级部门 切换页码
        groundhandleCurrentChange(val) {
            this.groundcurrent = val;
            this.groundgetList();
        },
        //单击当前行
        showauthories(row, event, column){
            // console.log(row.d_authories);

            let authories = window.localStorage.authories.split(",");

            if(authories.indexOf('151')  != -1){
                this.d_authories = row.d_authories;
                this.departmentId = row.id;
                //子组件重新渲染
                this.showPermission = false;
                this.$nextTick(function () {
                    this.showPermission = true; 
                });
            }
        },
        //部门类型  1综合 2 业务 3财务 4客服 5行政 6技术
        typeFun(row, column, cellValue, index){
            switch (cellValue) {
                case 1:
                    return '综合'
                case 2:
                    return '业务'
                case 3:
                    return '财务'
                case 4:
                    return '客服'
                case 5:
                    return '行政'
                case 6:
                    return '技术'
            }
        },
        //查看系统管理组
        look(data=Object()){
            conf.department.look(data,(state,res)=>{
                if (state == 'success'&&res.data.code == 0){
                    this.systemdata = res.data.data;

                    this.edit(res.data.data[0]);
                }else if(state == 'success'&&res.data.code != 0){
                    if(res.data.code == 401){
                        this.$router.push({name:'login'});   //登陆态失效，跳转至登录页
                    }else{
                        this.$message({
                            type: 'info',
                            message: res.data.msg
                        });
                    }
                }
            })
        },
        //三级部门列表
        groundgetList (data=Object()){
            data.page = this.groundcurrent;
            data.d_superior_id = this.d_superior_id;
            conf.department.list(data,(state,res)=>{
                if (state == 'success'&&res.data.code == 0){
                    console.log(res);
                    this.grounplist = res.data.data;
                }else if(state == 'success'&&res.data.code != 0){
                    if(res.data.code == 401){
                        this.$router.push({name:'login'});   //登陆态失效，跳转至登录页
                    }else if(res.data.code == -404){
                        this.grounplist = [];
                    }else{
                        this.$message({
                            type: 'info',
                            message: res.data.msg
                        });
                    }
                }
            })
        },
        //查看三级部门
        lookgrounp(row,data=Object()){
            // console.log(row);
            this.d_superior_id = row.id;  //上级部门id
            this.groundgetList();

            this.grounpcenterDialogVisible = true;
        },
        //关闭弹框
        dialogclose(){
            this.$refs['dform'].resetFields();
        },
        //获取部门员工
        obtainUser(data=Object()){
            this.userType = [];
            this.dform.charge = '';
            data.d_id = 0;
            conf.department.userOpt(data,(state,res)=>{
                if (state == 'success'&&res.data.code == 0){
                    this.userType = res.data.data;
                }else if(state == 'success'&&res.data.code != 0){
                    if(res.data.code == 401){
                        this.$router.push({name:'login'});   //登陆态失效，跳转至登录页
                    }else{
                        this.$message({
                            type: 'info',
                            message: res.data.msg
                        });
                    }
                }
            })
        },
    },
    mounted (){
        this.$nextTick(function(){
            this.getList();
            this.obtainUser();
        })
    },
        
  }
</script>